//
//  CDVKwais.m
//  cordova-plugin-jasonhe-kwais
//
//
//

#import "CDVKwais.h"

static int const MAX_THUMBNAIL_SIZE = 320;

@implementation CDVKwais

#pragma mark "API"
- (void)pluginInitialize {
    NSString* appId = [[self.commandDelegate settings] objectForKey:@"kwaisappid"];
    self.universalLink  = [[self.commandDelegate settings] objectForKey:@"universallink"];
    
    if (appId && ![appId isEqualToString:self.kwaisAppId]) {
        self.kwaisAppId = appId;
        

        if(![KSApi registerApp:appId universalLink:self.universalLink delegate:self]){
            NSLog(@"cordova-plugin-jasonhe-kwais has been init Fail!!!!.. Kwais SDK Version: %@. APP_ID: %@. universalLink:%@", [KSApi apiVersion], appId,self.universalLink);
            return;
        } else {
            NSLog(@"cordova-plugin-jasonhe-kwais has been initialized Success!!!!.. Kwais SDK Version: %@. APP_ID: %@. universalLink:%@", [KSApi apiVersion], appId,self.universalLink);
        }
    }
}

- (void)isKwaisAppInstalled:(CDVInvokedUrlCommand *)command
{
    CDVPluginResult *commandResult = [KSApi isAppInstalledFor:KSApiApplication_Kwai] ? [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:YES] : [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsBool:NO];

    [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}

- (void)share:(CDVInvokedUrlCommand *)command
{
    // if not installed
    if (![KSApi isAppInstalledFor:KSApiApplication_Kwai])
    {
        [self failWithCallbackID:command.callbackId withMessage:@"未安装快手"];
        return ;
    }

    // check arguments
    NSDictionary *params = [command.arguments objectAtIndex:0];
    if (!params)
    {
        [self failWithCallbackID:command.callbackId withMessage:@"参数格式错误"];
        return ;
    }

    // save the callback id
    self.currentCallbackId = command.callbackId;

    KSShareWebPageObject* object = [[KSShareWebPageObject alloc] init];
    KSShareMessageRequest *req = [[KSShareMessageRequest alloc] init];
    //       req.openID = [self selfOpenID];
    //       req.receiverOpenID = TARGET_OPEN_ID;
    
    // check the scene
    if ([params objectForKey:@"scene"])
    {
        req.shareScene = (int)[[params objectForKey:@"scene"] integerValue];
    }
    else
    {
        req.shareScene = KSShareScopeSession;
    }
    
   
    
    NSDictionary *message = [params objectForKey:@"message"];

    if (message)
    {
        object.title = [message objectForKey:@"title"];
        object.desc =  [message objectForKey:@"description"];
        object.linkURL = [message objectForKey:@"webpageUrl"];
//        NSString *imgUrl = [message objectForKey:@"imageUrl"];
//        object.thumbImage = [NSData  dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
        UIImage *image = [self getUIImageFromURL:[message objectForKey:@"imageUrl"]];
        object.thumbImage = UIImageJPEGRepresentation(image, 1);
        [KSApi sendRequest:req completion:nil];

        // async
        [self.commandDelegate runInBackground:^{
            req.shareObject = object;
            [KSApi sendRequest:req completion:^(BOOL success) {
                if (!success) {
                    [self failWithCallbackID:command.callbackId withMessage:@"发送请求失败"];
                    self.currentCallbackId = nil;
                }
            }];
        }];
    }
    
}

- (void)sendAuthRequest:(CDVInvokedUrlCommand *)command
{

    KSAuthRequest *req = [[KSAuthRequest alloc] init];

    // scope
    if ([command.arguments count] > 0)
    {
        req.scope = [command.arguments objectAtIndex:0];
    }
    else
    {
        req.scope = @"user_info";
    }

    req.h5AuthViewController = self.viewController;

    [KSApi sendRequest:req completion:^(BOOL success) {
        if (success) {
            // save the callback id
            self.currentCallbackId = command.callbackId;
        } else {
            [self failWithCallbackID:command.callbackId withMessage:@"发送请求失败"];

        }
    }];
}



- (void)jumpToKwais:(CDVInvokedUrlCommand *)command
{
    // check arguments
    NSString *url = [command.arguments objectAtIndex:0];
    if (!url || ![url hasPrefix:@"kuaishou://"])
    {
        [self failWithCallbackID:command.callbackId withMessage:@"参数格式错误"];
        return ;
    }

    NSURL *formatUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    if ([[UIApplication sharedApplication] canOpenURL:formatUrl]) {
        [[UIApplication sharedApplication] openURL:formatUrl];
    } else{
        [self failWithCallbackID:command.callbackId withMessage:@"未安装快手或其他错误"];
    }
    return ;
}



#pragma mark "KSApiDelegate"


- (void)ksApiDidReceiveResponse:(__kindof KSBaseResponse *)resp{
    BOOL success = NO;
    NSString *message = @"Unknown";
    NSDictionary *response = nil;

    switch (resp.error.code)
    {
        case KSErrorCodeSuccess:
            success = YES;
            break;

        case KSErrorCodeKwaiAppNotInstalled:
            message = @"快手 App 未安装 ";
            break;

        case KSErrorCodeCancelled:
            message = @"用户取消授权";
            break;

        case KSErrorCodeBadParameter:
            message = @"参数不合法";
            break;

        case KSErrorCodeDenied:
            message = @"请求被拒绝";
            break;

        default:
            message = @"未知错误";
    }

    if (success)
    {
        if ([resp isKindOfClass:[KSAuthResponse class]])
        {
            // fix issue that lang and country could be nil for iPhone 6 which caused crash.
            KSAuthResponse* authResp = (KSAuthResponse*)resp;
            response = @{
                         @"code": authResp.code != nil ? authResp.code : @"",
                         };

            CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:response];

            [self.commandDelegate sendPluginResult:commandResult callbackId:self.currentCallbackId];
        }
       
        else
        {
            [self successWithCallbackID:self.currentCallbackId];
        }
    }
    else
    {
        [self failWithCallbackID:self.currentCallbackId withMessage:message];
    }

    [self pluginInitialize];
    self.currentCallbackId = nil;
}

#pragma mark "CDVPlugin Overrides"

- (void)handleOpenURL:(NSNotification *)notification
{
    NSURL* url = [notification object];

    if ([url isKindOfClass:[NSURL class]] && [url.scheme isEqualToString:self.kwaisAppId])
    {
        [KSApi handleOpenURL:url];
    }
}

#pragma mark "Private methods"



- (NSData *)getNSDataFromURL:(NSString *)url
{
    NSData *data = nil;

    if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"])
    {
        data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    }
    else if ([url hasPrefix:@"data:image"])
    {
        // a base 64 string
        NSURL *base64URL = [NSURL URLWithString:url];
        data = [NSData dataWithContentsOfURL:base64URL];
    }
    else if ([url rangeOfString:@"temp:"].length != 0)
    {
        url =  [NSTemporaryDirectory() stringByAppendingPathComponent:[url componentsSeparatedByString:@"temp:"][1]];
        data = [NSData dataWithContentsOfFile:url];
    }
    else
    {
        // local file
        url = [[NSBundle mainBundle] pathForResource:[url stringByDeletingPathExtension] ofType:[url pathExtension]];
        data = [NSData dataWithContentsOfFile:url];
    }

    return data;
}

- (UIImage *)getUIImageFromURL:(NSString *)url
{
    NSData *data = [self getNSDataFromURL:url];
    UIImage *image = [UIImage imageWithData:data];

    if (image.size.width > MAX_THUMBNAIL_SIZE || image.size.height > MAX_THUMBNAIL_SIZE)
    {
        CGFloat width = 0;
        CGFloat height = 0;

        // calculate size
        if (image.size.width > image.size.height)
        {
            width = MAX_THUMBNAIL_SIZE;
            height = width * image.size.height / image.size.width;
        }
        else
        {
            height = MAX_THUMBNAIL_SIZE;
            width = height * image.size.width / image.size.height;
        }

        // scale it
        UIGraphicsBeginImageContext(CGSizeMake(width, height));
        [image drawInRect:CGRectMake(0, 0, width, height)];
        UIImage *scaled = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return scaled;
    }

    return image;
}

- (void)successWithCallbackID:(NSString *)callbackID
{
    [self successWithCallbackID:callbackID withMessage:@"OK"];
}

- (void)successWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}

- (void)failWithCallbackID:(NSString *)callbackID withError:(NSError *)error
{
    [self failWithCallbackID:callbackID withMessage:[error localizedDescription]];
}

- (void)failWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}
    
@end
